extends TextureButton

@export var animation_player: AnimationPlayer
@export var input_server_ip: LineEdit
@export var input_server_port: LineEdit

var http_request: HTTPRequest
var url: String = "https://bgithub.xyz/shikeik/project-template/releases/download/multiplayergamedemo/official-server.json"
var json: JSON  # 声明 JSON 类实例

var requesting := false

func _ready() -> void:
	
	# 创建并添加 HTTPRequest 实例
	http_request = HTTPRequest.new()
	add_child(http_request)
	# 创建 JSON 实例
	json = JSON.new()
	# 连接请求完成信号
	http_request.request_completed.connect(_on_request_completed)


func _process(delta: float) -> void:
	if requesting:
		animation_player.play("loading")
	else:
		animation_player.play("RESET")
	pass

func request() -> void:
	if requesting == true: 
		LogLabel.printerr_log(["重复请求"])
		return
	requesting = true
	var timeout_seconds := 20.0
	LogLabel.print_log(["开始检查官网服务器最新ip-port信息...超时:", timeout_seconds, "s"])
	get_tree().create_timer(timeout_seconds-1).timeout.connect(_on_request_timeout)
	# 设置请求头（添加 User-Agent）
	var headers = ["User-Agent: Godot Engine"]
	# 发起 HTTP 请求，附加请求头
	var error = http_request.request(url, headers)
	if error != OK:
		LogLabel.printerr_log(["请求失败: ", error])
	pass


func _on_request_timeout() -> void: 
	if requesting: 
		LogLabel.print_log(["检查最新信息的请求已超时."])
		requesting = false
	pass

func _on_request_completed(result, response_code, headers, body):
	if !requesting: 
		#LogLabel.print_log(["请求完成, 但已超时."])
		return
	if response_code == 200:
		# 解析 JSON 数据
		var json_result = json.parse(body.get_string_from_utf8())
		
		if json_result == OK:
			var json_data = json.get_data()  # 获取解析后的数据，返回 Dictionary 或 Array
			var ip := str(json_data["ip"])
			var port := int(json_data["port"])
			#var server_status := "在线" if int(json_data["server_status"])==1 else "离线"
			input_server_ip.text = ip
			input_server_port.text = str(port)
			LogLabel.print_log(["官网服务器数据解析成功: ", json_data])
			#LogLabel.print_log(["当前服务器状态: ", server_status])
		else:
			LogLabel.printerr_log(["JSON 解析失败"])
	else:
		LogLabel.printerr_log(["官网服务器解析失败, 状态码:", response_code])
	requesting = false


func _on_button_up() -> void:
	request()
	pass # Replace with function body.
